package paypal;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.io.UnsupportedEncodingException;
import java.io.Writer;
import java.net.HttpURLConnection;
import java.net.ProtocolException;
import java.net.URL;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.List;

import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicHeader;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.protocol.HTTP;

public class Utils {

	public static StringBuilder getBaseStringRequest() {
		StringBuilder sRequest = new StringBuilder();
		try {
			// requestEnvelope fields
			sRequest.append("requestEnvelope.errorLanguage=");

			sRequest.append(URLEncoder.encode(Const.ERROR_LANGUAGE, "UTF-8"));

			sRequest.append("&requestEnvelope.detailLevel=");
			sRequest.append(URLEncoder.encode(Const.DETAIL_LEVEL, "UTF-8"));

			// clientDetails fields
			sRequest.append("&clientDetails.applicationId=");
			sRequest.append(URLEncoder.encode(Const.APP_ID, "UTF-8"));

			sRequest.append("&clientDetails.deviceId=");
			sRequest.append(URLEncoder.encode(Const.DEVICE_ID, "UTF-8"));

			sRequest.append("&clientDetails.ipAddress=");
			sRequest.append(URLEncoder.encode(Const.IP_ADDRESS, "UTF-8"));

			sRequest.append("&clientDetails.partnerName=");
			sRequest.append(URLEncoder.encode(Const.PARTNER_NAME, "UTF-8"));

			// request specific data fields

			sRequest.append("&cancelUrl=");
			sRequest.append(URLEncoder.encode(Const.CANCEL_URL, "UTF-8"));

			sRequest.append("&returnUrl=");
			sRequest.append(URLEncoder.encode(Const.RETURN_URL, "UTF-8"));

			sRequest.append("&currencyCode=");
			sRequest.append(URLEncoder.encode(Const.CURRENCY_CODE, "UTF-8"));

			sRequest.append("&feesPayer=");
			sRequest.append(URLEncoder.encode(Const.FEES_PAYER, "UTF-8"));

		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		}

		// sRequest.append("&trackingId=");
		// sRequest.append(System.Guid.NewGuid().ToString());

		return sRequest;
	}

	/*
	 * public static String doWebRequest(String endpointURL, String
	 * requestString) { HttpWebRequest oPayRequest = (HttpWebRequest) WebRequest
	 * .Create(endpointURL);
	 * 
	 * oPayRequest.Method = "POST"; oPayRequest.ContentLength =
	 * requestString.Length; oPayRequest.ContentType =
	 * "application/x-www-form-urlencoded";
	 * 
	 * // Set the HTTP Headers
	 * oPayRequest.Headers.Add("X-PAYPAL-SECURITY-USERID", Const.API_USERNAME);
	 * oPayRequest.Headers.Add("X-PAYPAL-SECURITY-PASSWORD",
	 * Const.API_PASSWORD);
	 * oPayRequest.Headers.Add("X-PAYPAL-SECURITY-SIGNATURE",
	 * Const.API_SIGNATURE); oPayRequest.Headers.Add("X-PAYPAL-SERVICE-VERSION",
	 * Const.VERSION); oPayRequest.Headers.Add("X-PAYPAL-APPLICATION-ID",
	 * Const.APP_ID); oPayRequest.Headers.Add("X-PAYPAL-REQUEST-DATA-FORMAT",
	 * Const.REQUEST_DATA_BINDING);
	 * oPayRequest.Headers.Add("X-PAYPAL-RESPONSE-DATA-FORMAT",
	 * Const.RESPONSE_DATA_BINDING);
	 * 
	 * // Send the request StreamWriter oStreamWriter = new StreamWriter(
	 * oPayRequest.GetRequestStream()); oStreamWriter.Write(requestString);
	 * oStreamWriter.Close();
	 * 
	 * // Get the response HttpWebResponse oPayResponse = (HttpWebResponse)
	 * oPayRequest .GetResponse(); StreamReader oStreamReader = new
	 * StreamReader( oPayResponse.GetResponseStream()); string sResponse =
	 * oStreamReader.ReadToEnd(); oStreamReader.Close();
	 * 
	 * return HttpUtility.UrlDecode(sResponse); }
	 */

	/**
	 * Sends an HTTP GET request to a url
	 * 
	 * @param endpoint
	 *            - The URL of the server. (Example:
	 *            " http://www.yahoo.com/search")
	 * @param requestParameters
	 *            - all the request parameters (Example:
	 *            "param1=val1&param2=val2"). Note: This method will add the
	 *            question mark (?) to the request - DO NOT add it yourself
	 * @return - The response from the end point
	 */

	/*
	 * public static String sendGetRequest(String endpoint, String
	 * requestParameters) { String result = null; if
	 * (endpoint.startsWith("http://")) { // Send a GET request to the servlet
	 * try {
	 * 
	 * // Send data String urlStr = endpoint; if (requestParameters != null &&
	 * requestParameters.length() > 0) { urlStr += "?" + requestParameters; }
	 * URL url = new URL(urlStr); URLConnection conn = url.openConnection();
	 * 
	 * // Get the response BufferedReader rd = new BufferedReader(new
	 * InputStreamReader( conn.getInputStream())); StringBuffer sb = new
	 * StringBuffer(); String line; while ((line = rd.readLine()) != null) {
	 * sb.append(line); } rd.close(); result = sb.toString(); } catch (Exception
	 * e) { e.printStackTrace(); } } return result; }
	 */
	/**
	 * Reads data from the data reader and posts it to a server via POST
	 * request. data - The data you want to send endpoint - The server's address
	 * output - writes the server's response to output
	 * 
	 * @throws Exception
	 */
	/*
	 * public static void postData(Reader data, URL endpoint, Writer output)
	 * throws Exception { HttpURLConnection urlc = null; //----------------- try
	 * { urlc = (HttpURLConnection) endpoint.openConnection(); try {
	 * 
	 * urlc.setRequestMethod("POST");//-----------------
	 * 
	 * } catch (ProtocolException e) { throw new Exception(
	 * "Shouldn't happen: HttpURLConnection doesn't support POST??", e); }
	 * 
	 * urlc.setDoOutput(true);//-----------------
	 * urlc.setDoInput(true);//-----------------
	 * urlc.setUseCaches(false);//-----------------
	 * urlc.setAllowUserInteraction(false);//-----------------
	 * 
	 * urlc.setRequestProperty("Content-type",
	 * "application/x-www-form-urlencoded; charset=" +
	 * "UTF-8");//-----------------
	 * urlc.setRequestProperty("X-PAYPAL-SECURITY-USERID", Const.API_USERNAME);
	 * urlc.setRequestProperty("X-PAYPAL-SECURITY-PASSWORD",
	 * Const.API_PASSWORD);
	 * urlc.setRequestProperty("X-PAYPAL-SECURITY-SIGNATURE",
	 * Const.API_SIGNATURE); urlc.setRequestProperty("X-PAYPAL-SERVICE-VERSION",
	 * Const.VERSION); urlc.setRequestProperty("X-PAYPAL-APPLICATION-ID",
	 * Const.APP_ID); urlc.setRequestProperty("X-PAYPAL-REQUEST-DATA-FORMAT",
	 * Const.REQUEST_DATA_BINDING);
	 * urlc.setRequestProperty("X-PAYPAL-RESPONSE-DATA-FORMAT",
	 * Const.RESPONSE_DATA_BINDING);
	 * 
	 * OutputStream out = urlc.getOutputStream();
	 * 
	 * try { Writer writer = new OutputStreamWriter(out, "UTF-8");
	 * writer.write(arg0) //pipe(data, writer); writer.close(); } catch
	 * (IOException e) { throw new Exception("IOException while posting data",
	 * e); } finally { if (out != null) out.close(); }
	 * 
	 * InputStream in = urlc.getInputStream(); try { Reader reader = new
	 * InputStreamReader(in); pipe(reader, output); reader.close(); } catch
	 * (IOException e) { throw new
	 * Exception("IOException while reading response", e); } finally { if (in !=
	 * null) in.close(); }
	 * 
	 * } catch (IOException e) { throw new
	 * Exception("Connection error (is server running at " + endpoint + " ?): "
	 * + e); } finally { if (urlc != null) urlc.disconnect(); } }
	 *//**
	 * Pipes everything from the reader to the writer via a buffer
	 */
	/*
	 * private static void pipe(Reader reader, Writer writer) throws IOException
	 * { char[] buf = new char[1024]; int read = 0; while ((read =
	 * reader.read(buf)) >= 0) { writer.write(buf, 0, read); } writer.flush(); }
	 */
	public static String doWebRequest(String contentData, String endpoint)
			throws IOException {

		HttpURLConnection urlc = null; // -----------------

		BufferedReader respContent = null;
		PrintWriter display;
		String respLine;
		String responseRS = "";

		URL url = new URL(endpoint);

		try {
			urlc = (HttpURLConnection) url.openConnection();
			try {
				urlc.setRequestMethod("POST");// -----------------

			} catch (ProtocolException e) {
			}

			urlc.setDoOutput(true);// -----------------
			urlc.setDoInput(true);// -----------------
			urlc.setUseCaches(false);// -----------------
			urlc.setAllowUserInteraction(false);// -----------------

			urlc.setRequestProperty("Content-type",
					"application/x-www-form-urlencoded; charset=" + "UTF-8");// -----------------

			// SendReq
			OutputStream out = urlc.getOutputStream();
			try {
				Writer writer = new OutputStreamWriter(out, "UTF-8");
				writer.write(contentData);
				writer.close();
			} catch (IOException e) {
				throw new Exception("IOException while posting data", e);
			} finally {
				if (out != null)
					out.close();
			}

			// ReadRes
			respContent = new BufferedReader(new InputStreamReader(
					urlc.getInputStream()));
			display = new PrintWriter(System.out);
			while ((respLine = respContent.readLine()) != null) {
				/* display.println(respLine); */
				responseRS += respLine + '\n';
			}

			display.flush();
			respContent.close();
			urlc.disconnect();

		} catch (Exception e) {
		}
		return responseRS;
	}

	public static String doWebRequestNew(String endpoint, String contentData) {

		HttpClient client = new DefaultHttpClient();
		HttpPost post = new HttpPost(endpoint);
		String responseStr = "";
		try {
			/*
			 * List<NameValuePair> nameValuePairs = new
			 * ArrayList<NameValuePair>(1); nameValuePairs.add(new
			 * BasicNameValuePair("registrationid", "123456789"));
			 * post.setEntity(new UrlEncodedFormEntity(nameValuePairs));
			 */

			StringEntity se = new StringEntity(contentData);
			se.setContentEncoding(new BasicHeader(HTTP.CONTENT_TYPE,
					"application/x-www-form-urlencoded; charset=UTF-8"));

			post.setHeader("X-PAYPAL-SECURITY-USERID", Const.API_USERNAME);
			post.setHeader("X-PAYPAL-SECURITY-PASSWORD", Const.API_PASSWORD);
			post.setHeader("X-PAYPAL-SECURITY-SIGNATURE", Const.API_SIGNATURE);
			post.setHeader("X-PAYPAL-SERVICE-VERSION", Const.VERSION);
			post.setHeader("X-PAYPAL-APPLICATION-ID", Const.APP_ID);
			post.setHeader("X-PAYPAL-REQUEST-DATA-FORMAT",
					Const.REQUEST_DATA_BINDING);
			post.setHeader("X-PAYPAL-RESPONSE-DATA-FORMAT",
					Const.RESPONSE_DATA_BINDING);
			post.setEntity(se);

			// get Response
			HttpResponse response = client.execute(post);
			BufferedReader rd = new BufferedReader(new InputStreamReader(
					response.getEntity().getContent()));
			String line = "";
			while ((line = rd.readLine()) != null) {
				System.out.println(line);
				responseStr += line + '\n';
			}

		} catch (IOException e) {
			e.printStackTrace();
		}

		return responseStr;
	}
}
